-- 是否已抢
local exists = redis.call('HEXISTS', KEYS[2], ARGV[1])
if exists == 1 then
    return '1'
end
-- 是否还有红包
local residualCount = tonumber(redis.call("hget", KEYS[1], 'residualCount'))
if residualCount <= 0 then
    return '-1'
end

local residualAmount = tonumber(redis.call("hget", KEYS[1], 'residualAmount'))
local isOnlyMinAmount = tonumber(redis.call('hget', KEYS[1], "isOnlyMinAmount"))
if residualCount == 1 then
    local money = string.format("%.2f",residualAmount)
    local luaString = '{"money": "%s", "grabTime": "%s"}'
    local newStr = string.format(luaString, money,ARGV[2])
    -- 记录红包被抢完时间点
    redis.call('hset', KEYS[1], "burnoutTime", ARGV[2])
    redis.call("hset", KEYS[2], ARGV[1], newStr)
    redis.call("hset", KEYS[1], 'residualAmount',0)
    redis.call("hset", KEYS[1], 'residualCount', 0)
    return money
end

local money = 0.01;
if isOnlyMinAmount == 0 then
    math.randomseed(tostring(redis.call('TIME')[1] * 1000000 + redis.call('TIME')[2]))
    local average = residualAmount / residualCount
    local maxMoney = average * 2
    money = math.random() * maxMoney
    money = math.max(money, 0.01)
    if residualAmount > residualCount then
        local min = residualAmount - residualCount + 1
        money = math.min(money, min)
    end
end



residualAmount=residualAmount-money
money = string.format("%.2f",money)
local luaString = '{"money": "%s", "grabTime": "%s"}'
local newStr = string.format(luaString, money,ARGV[2])
redis.call("hset", KEYS[2], ARGV[1], newStr)
redis.call("hset", KEYS[1], 'residualAmount',string.format("%.2f",residualAmount))
redis.call("hset", KEYS[1], 'residualCount', residualCount-1)
redis.call('expire', KEYS[2], 3600*48)
return money